import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../assets/color_config.dart';
import '../common/app_config.dart';
import '../http/http.dart';
import '../utils/toast_utils.dart';
import 'button_widget.dart';
import 'image_widget.dart';

class ImgCodeDialog extends StatefulWidget {
  final String imgUrl;
  final String mobile;
  final String region;
  FocusNode? focusNode;

  ImgCodeDialog({
    Key? key,
    required this.imgUrl,
    required this.mobile,
    required this.region,
    required this.onChanged,
    this.focusNode,
  }) : super(key: key);

  final ValueChanged<String> onChanged;

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _ImgCodeDialogState();
  }
}

class _ImgCodeDialogState extends State<ImgCodeDialog>
    with WidgetsBindingObserver {
  TextEditingController imgCodeController = TextEditingController();
  late FocusNode focusNode;
  String codeImgUrl = "";
  double keyBoardBottom = 50.w;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    focusNode = widget.focusNode ?? FocusNode();
    //图片验证码只能
    codeImgUrl = "${AppConfig().getImageHost()}${widget.imgUrl}";
    //初始化
    // WidgetsBinding.instance.addObserver(this);
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Material(
      type: MaterialType.transparency,
      child: Center(
        child: Column(
          children: [
            Expanded(flex: 1,child: Container(),),
            Container(
              width: 300.w,
              //height: 190.w,
              // margin: EdgeInsets.only(bottom: keyBoardBottom),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8.w),
              ),
              child: Column(
                children: [
                  Container(
                    padding: EdgeInsets.only(top: 10.w, left: 30.w, right: 30.w),
                    child: Text(
                      "show_captcha_title".tr,
                      textAlign: TextAlign.center,
                      style: TextStyle(fontSize: 16.sp,color: Colors.black),
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.only(left: 30.w, top: 25.w,right: 30.w),
                    width: double.infinity,
                    child: Row(
                      children: [
                        Expanded(
                          child:Column(
                            children: [
                              Container(
                                width: 150.w,
                                height: 40.w,
                                alignment: Alignment.centerLeft,
                                child: TextField(
                                  controller: imgCodeController,
                                  style: TextStyle(
                                    color: ColorConfig.colorBlack,
                                    fontSize: 14.sp,
                                  ),
                                  keyboardType: TextInputType.number,
                                  focusNode: focusNode,
                                  decoration: InputDecoration(
                                    hintText: "et_captcha_placeholder".tr,
                                    border: InputBorder.none,
                                  ),
                                ),
                              ),
                              SizedBox(
                                width: 150.w,
                                height: 1.w,
                                child: const Divider(
                                  color: Colors.grey,
                                ),
                              ),
                            ],
                          ),
                        ),
                        SizedBox(width: 10.w,),
                        GestureDetector(
                          child: Container(
                            color: ColorConfig.colorF5,
                            // margin: EdgeInsets.only(right: 20.w),
                            width: 65.w,
                            height: 30.w,
                            child: ImageWidget(
                              url: codeImgUrl,
                              width: double.infinity,
                              height: double.infinity,
                            ),
                          ),
                          onTap: () {
                            refreshCodeImg();
                          },
                        ),
                      ],
                    ),
                  ),
                  SizedBox(height: 30.w,),
                  Container(
                    padding: EdgeInsets.only(left: 30.w, right: 30.w,),
                    child: ButtonWidget(
                      onPressed: confirmImgCode,
                      child: Container(
                        height: 40.w,
                        width: double.infinity,
                        decoration: BoxDecoration(
                          color: ColorConfig.colorPrimary,
                          borderRadius: BorderRadius.circular(5.w),
                        ),
                        child: Center(
                          child: Text(
                            "title_ok".tr,
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 14.sp,
                              fontWeight: FontWeight.normal,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(height: 15.w,),
                ],
              ),
            ),
            Expanded(flex: 1,child: Container(),),
          ],
        ),
      ),
    );
  }

  ///确认图形验证码
  void confirmImgCode() {
    String imgCode = imgCodeController.text;
    if (imgCode.isEmpty) {
      showToast("message_image_captcha_error".tr);
      return;
    }
    widget.onChanged(imgCode);
    Navigator.of(context).pop();
  }

  ///刷新图片验证码
  refreshCodeImg() {
    Map params = {"mobile": widget.mobile, "region": widget.region};
    Http().post(apiGetCaptUrl, body: params, loading: true, success: (res) {
      if (res.code == apiSuccess) {
        String captchaUrl = res.data["captchaUrl"];
        codeImgUrl = "${AppConfig().getImageHost()}$captchaUrl";
        setState(() {});
      } else {
        showToast(res.message);
      }
    });
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    // WidgetsBinding.instance.addPostFrameCallback((_) {
    //   if(MediaQuery.of(context).viewInsets.bottom==0){
    //     //关闭键盘
    //     keyBoardBottom = 0;
    //   }else{
    //     //显示键盘
    //     keyBoardBottom = 50.w;
    //   }
    //   setState(() {});
    // });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    focusNode.dispose();
    //销毁
    // WidgetsBinding.instance.removeObserver(this);
  }
}
